"""
菜单文件
"""
from django.shortcuts import render, redirect, HttpResponse
from rbac import models
from django.urls import reverse
from rbac.forms.menu import MenuModelForm,SecodMenuModelForm
from rbac.service.urls import memory_reverse


def menu_list(request):
    """
    菜单和权限列表
    :param request:
    :return:
    """
    menus = models.Menu.objects.all()
    menu_id = request.GET.get('mid')  # 用户的一级菜单
    second_menu_id = request.GET.get('sid')
    if menu_id:
        second_menus = models.Permission.objects.filter(menu_id=menu_id).values()
    else:
        second_menus = []
    return render(
        request,
        'rbac/menu_list.html'
        , {
            'menus': menus,
            'menu_id': menu_id,
            'second_menus': second_menus,
            'second_menu_id': second_menu_id
        })


def menu_add(request):
    """
    添加一级菜单
    :param request:
    :return:
    """
    if request.method == "GET":
        form = MenuModelForm()
        return render(request, 'rbac/role_add.html', {'form': form})
    form = MenuModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(memory_reverse(request, 'rbac:menu_list'))
    return render(request, 'rbac/role_add.html', {'form': form})


def menu_edit(request, pk):
    obj = models.Menu.objects.filter(id=pk).first()
    if not obj:
        return HttpResponse('菜单不存在')
    if request.method == "GET":
        form = MenuModelForm(instance=obj)  # instance默认值
        return render(request, 'rbac/role_add.html', {'form': form})
    form = MenuModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(memory_reverse(request, 'rbac:menu_list'))
    return redirect(reverse('rbac:menu_list'))


def menu_del(request, pk):
    url = memory_reverse(request, 'rbac:menu_list')
    if request.method == "GET":
        return render(request, 'rbac/delete.html', {'cancel': url})
    models.Menu.objects.filter(id=pk).delete()
    return redirect(url)


def second_menu_add(request, menu_id):
    """
    添加二级菜单
    :param request:
    :param menu_id: 已选择的一级菜单ID
    :return:
    """
    if request.method == "GET":
        form = SecodMenuModelForm()
        return render(request, 'rbac/role_add.html', {'form': form})
    form = SecodMenuModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(memory_reverse(request, 'rbac:menu_list'))
    return render(request, 'rbac/role_add.html', {'form': form})
